//
//  WBNetworkManager+Extension.swift
//  Weibo
//
//  Created by cc on 9/15/17.
//  Copyright © 2017 cc. All rights reserved.
//

import Foundation




// MARK: - 封装 新浪微博的网络请求方法
extension WBNetworkManager {
    
    
    
    /// 加载微博数据字典数组
    ///
    ///   - since_id: 返回ID比since_id大的微博(即比since_id時間晚的微博， 默認為0)
    ///   - max_id:   返回ID小於或等於max_id的微博，默認為0
    /// - Parameter complete: 完成回调[微博字典数组 / 是否成功]
    @objc func statusList(since_id: Int64 = 0, max_id: Int64 = 0, complation:@escaping (_ list: [[String: Any]]?,_ isSuccess: Bool)->()) {
        
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //        let params = ["access_token": "2.00NKbMECwXsXJB81a1831dffN9yRFC"]
        
        
        //Swift 中， Int 能轉 AnyObject， 但是 Int64不行
        let params = ["since_id": since_id, "max_id": max_id > 0 ? max_id - 1 : 0]
        
        tokenRequest(URLString: urlString, parameters: params) { (json , isSuccess) in
            
            // 从  json 中获取 statuses 字典数组
            // 如果 as？ 失败， result = nil
            //提示： 服務器返回的字典數組，就是按照時間的倒序排序的
            
            guard let json = json else {
                return
            }
            let result = (json as! NSDictionary)["statuses"] as? [[String: Any]]
            
            complation(result, true)
            
        }
        
    }
    
    
    /// 返回微博的未读数量
    @objc func unreadCount(completion:@escaping (_ count: Int)->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            let dict = json as? [String:Any]
            
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
    }
}




// MARK: - 发布微博
extension WBNetworkManager {

    /// 发布微博
    ///
    /// - Parameters:
    ///   - text: 要发布的文本
    ///   - image: 要上传的图像 ，为nil 时， 发布纯文本微博
    ///   - completion: 回调
    @objc func postStatus(text: String, image: UIImage?, completion:@escaping (_ result:[String: Any]?,_ isSuccess: Bool)->()) -> () {
        //1.url
        let urlString: String
        
        //根据是否有图像， 选择不同的接口地址
        if image == nil {
            urlString = "https://api.weibo.com/2/statuses/update.json"
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        //2. 参数字典
        let params = ["status": text]
        
        //3.如果图像不为空，需要设置 name 和 data
        
        var name: String?
        var data: Data?
        
        
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
        }
        
        //4.发起网络请求
        
        tokenRequest(method: .POST, URLString: urlString, parameters: params, name: name, data: data) { (json, isSuccess) in
            completion(json as? [String: Any], isSuccess)
        }
    }
}



// MARK: - Get User's Information
extension WBNetworkManager {
    
    
    /// Loading current User's Information, 用戶登錄後立即執行
    @objc func loadUserInfo(completion: @escaping (_ dict:[String: Any])->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard let uid = userAccount.uid else {
            return
        }
        let params = ["uid": uid]
        
        //發起網絡請求
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            //完成回調
            completion((json as? [String: Any]) ?? [:])
        }
    }
}



// MARK: - OAuth相关方法
extension WBNetworkManager {

    /// 加载accessToken
    ///
    /// - Parameters:
    ///   - code: 授權碼
    ///   - completion: 完成回調[是否成功]
    @objc func loadAccessToken (code: String,completion: @escaping (_ isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": WBAppKey, "client_secret": WBAppSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": WBRedirectUrl ]
        
        //发起网络请求
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            
            //如果請求失敗，堆用戶賬戶不會有影響
            //直接用字典设置 userAccount 的属性
            self.userAccount.yy_modelSet(with: (json as? [String: Any]) ?? [:])
            
            print(self.userAccount)
            
            //加載當前用戶信息
            self.loadUserInfo(completion: { (dict) in
                
                //使用用户信息字典设置用户帐户信息昵称和头像
                self.userAccount.yy_modelSet(with: dict)
                
                //保存模型
                self.userAccount.saveAccount()
                
                //用戶信息加載完成再回調
                completion(isSuccess)
            })
            
        }
    }
}








